// 1->common.js中引入axios
import axios from 'axios';
// 引入Cookie
import Cookies from 'js-cookie';

axios.defaults.timeout = 180000 // 超时时间

// http request 拦截器
axios.interceptors.request.use(
  config => {
    // 注意使用的时候需要引入cookie方法，推荐js-cookie
    let token = Cookies.get('token')
    // 如果是post请求 请求体自动加上token
    if (config.method === 'post') {
      if (token) {
        config.headers = {
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Token': token
        }
      }
    } else if (config.method === 'get') {
      config.headers = {}
      if (token) {
        config.headers = {
          'Content-Type': 'application/x-www-form-urlencoded',
          'User-Token': token
        }
      }
    }
    return config
  },
  error => {
    // return Promise.reject(err)
    console.log(error)
  }
)

// 2->对get请求传递过来的参数处理
function paramsToUrl (url, params) {
  if (!params) return url
  for (var key in params) {
    if (params[key] && params[key] !== 'undefined') {
      if (url.indexOf('?') !== -1) {
        url += '&' + '' + key + '=' + params[key] || '' + '';
      } else {
        url += '?' + '' + key + '=' + params[key] || '' + '';
      }
    }
  }
  return url
}

// 3->在common.js中封装公用方法-----封装请求的方法
export function requireData (url, params, type, item) {
  if (!url) return false
  switch (item) {
    case 'back':
      url = axios.defaults.baseM1URL + url
      break;
    case 'before':
      url = axios.defaults.baseM2URL + url
      break;
    case 'taskcenter':
      url = axios.defaults.baseM3URL + url
      break;
    case 'core':
      url = axios.defaults.baseM4URL + url
      break;
  }
  if (type === 'get') {
    url = paramsToUrl(url, params)
    return new Promise((resolve, reject) => {
      axios
        .get(url, params)
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  } else if (type == 'post') {
    return new Promise((resolve, reject) => {
      axios({
        url: url,
        method: 'POST',
        data: params,
        transformRequest: [
          function (data) {
            let ret = '';
            for (let it in data) {
              ret +=
                encodeURIComponent(it) +
                '=' +
                encodeURIComponent(data[it]) +
                '&';
            }
            return ret
          }
        ]
      })
        .then(res => {
          if (res.data.code === 1001) {
            this.$Message.warning('用户超时' + res.data.message)
            this.$router.push({
              path: '/'
            })
            return;
          }
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
    })
  }
}
